/**
 * http.js 
 * 作用：实现ajax 的请求封装 get  post  ajax 
 * author:cometang  date:2022-5-5
 */

 const BASE_URL = 'http://139.9.177.51:8099'


 //只负责 将对象转换为 字符串
 // 异步：定时器/延时器  ajax  promise 
 // obj:  {name:"张三",age:40,id:1000};
 // str: 'name=张三&age=40&id=1000'
 function formatObj(obj){
     let str = '';
     for(key in obj){
         //key : 'name'
         //obj[key]
         str+=  '&'+key+'='+obj[key]
     }
     //删除第一个 &
     str = str.slice(1);
     return str
 }
 
 const http = {
     //get请求
     // '/users/add'
     get:function(url,data,callback){
         let xhr = new XMLHttpRequest();
         // 数据如何转换
         // url+ ? key=val&key1=val1&key2=val2
         xhr.open('get',BASE_URL+url+'?'+formatObj(data))
         xhr.send();
         xhr.onreadystatechange = function(){
             if(xhr.readyState ===4 && xhr.status ===200){
                 callback(JSON.parse(xhr.responseText));
             }
         }
     },
 
 
     //post 请求
     post:function(url,data,callback){
         let xhr = new XMLHttpRequest();
         // 数据如何转换
         xhr.open('post',BASE_URL+url);
         //form表单数据
         // xhr.setRequestHeader('content-type','application/x-www-form-urlencoded')
              //key=val& key1=val1 &key2=val2
         // xhr.send(formatObj(data));
         // json 格式数据
         xhr.setRequestHeader('content-type','application/json')
         xhr.send(JSON.stringify(data));
         xhr.onreadystatechange = function(){
             if(xhr.readyState ===4 && xhr.status ===200){
                 callback(JSON.parse(xhr.responseText));
             }
         }
     },
     //万能请求
     ajax:function(obj){
         //判断 是get
         if(obj.type =='get'){
             this.get(BASE_URL,obj.url,obj.data,obj.success)
         }
         //post 
         if(obj.type =='post'){
             this.post(BASE_URL,obj.url,obj.data,obj.success)
         } 
     }
 
 }
 
 //将http对象 挂载到 window 上
 window.$http = http;